<?php
/***********************************************************************
  
  Copyright (C) 2005  Vincent Garnier (vin100@forx.fr)

  This software is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 2 of the License,
  or (at your option) any later version.

  This software is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  MA  02111-1307  USA

************************************************************************/


/************************************************************************\
	Configuration des limites / Limits configuration
\************************************************************************/

$smilies_config_image_size = 10240;	// max upload image size in bytes
$smilies_config_image_width = 20;	// max upload image width in pixels
$smilies_config_image_height = 20;	// max upload image height in pixels


/************************************************************************\
	Ne pas modifier ci-dessous / Do not edit bellow
\************************************************************************/

// Make sure no one attempts to run this script "directly"
if (!defined('PUN'))
    exit;

// Tell admin_loader.php that this is indeed a plugin and that it is loaded
define('PUN_PLUGIN_LOADED', 1);
define('PLUGIN_VERSION', '1.3.1');
define('PLUGIN_URL', $_SERVER['REQUEST_URI']);

// Load the smilies language files
require PUN_ROOT.'lang/'.$pun_user['language'].'/smilies.php';

// Display the smiley set
if (file_exists(PUN_ROOT.'cache/cache_smilies.php')) {
    include PUN_ROOT.'cache/cache_smilies.php';
} else {
    require_once PUN_ROOT.'include/cache_smilies.php';
    generate_smiley_cache();
    require PUN_ROOT.'cache/cache_smilies.php';
}

// Change smilies texts and positions
if (isset($_POST['reord']))
{
	$smilies_order = array_map('intval',array_map('trim',$_POST['smilies_order']));
	$smilies_code = array_map('trim',$_POST['smilies_code']);	
	
	// Checking smilies codes
	$smiley_dups = array();
	
	foreach($smilies_code as $i=>$v)
	{
		if ($v == '')
			message($lang_smiley['Create Smiley Code None']);
		
		if (in_array($v, $smiley_dups))
			message(sprintf($lang_smiley['Duplicate smilies code'],$v));
		else
			$smiley_dups[] = $v;
	}
	
	$result = $db->query('SELECT id FROM '.$db->prefix.'smilies ORDER BY disp_position') or error('Unable to retrieve smilies', __FILE__, __LINE__, $db->error());
	
	while ($db_smilies = $db->fetch_assoc($result))
		$db->query('UPDATE '.$db->prefix.'smilies SET disp_position='.$smilies_order[$db_smilies['id']].', text=\''.$smilies_code[$db_smilies['id']].'\' WHERE id='.$db_smilies['id']) or error('Unable to edit smilies', __FILE__, __LINE__, $db->error());
		
	require_once PUN_ROOT.'include/cache_smilies.php';
	generate_smiley_cache();
	
	if (file_exists(PUN_ROOT.'include/cache_puntoolbar.php'))
	{
		require_once PUN_ROOT.'include/cache_puntoolbar.php';
		generate_ptb_cache();
		generate_ptb_cache('quickreply');
	}

	redirect(PLUGIN_URL, $lang_smiley['Smilies edited']);
}

// Remove smilies
elseif (isset($_POST['remove']))
{
	$rem_smilies = array_map('trim', $_POST['rem_smilies']);
	
	foreach (array_keys($rem_smilies) as $id)
		$db->query('DELETE FROM '.$db->prefix."smilies WHERE id = '".$id."'") or error('Unable to delete smiley', __FILE__, __LINE__, $db->error());
		
	require_once PUN_ROOT.'include/cache_smilies.php';
	generate_smiley_cache();
	
	if (file_exists(PUN_ROOT.'include/cache_puntoolbar.php'))
	{
		require_once PUN_ROOT.'include/cache_puntoolbar.php';
		generate_ptb_cache();
		generate_ptb_cache('quickreply');
	}

	redirect(PLUGIN_URL, $lang_smiley['Delete Smiley Redirect']);
}


// Delete images
elseif (isset($_POST['delete']))
{
	$del_smilies = array_map('trim', $_POST['del_smilies']);
	
	$to_delete = array();
	$images_affected = array();
	$not_deleted = array();
	
	foreach (array_keys($del_smilies) as $img)
	{
		if (!in_array($img, $smiley_img))
			$to_delete[] = $img;
		else
			$images_affected[] = $img;
	}
	
	if (!empty($images_affected))
		message(sprintf($lang_smiley['Images affected'], implode(', ', $images_affected)));

	else {
		foreach ($to_delete as $img)
		{
			if (!@unlink(PUN_ROOT.'img/smilies/'.$img))
				$not_deleted[] = $img;
		}
	}
		
	if (!empty($not_deleted))
		$message = sprintf($lang_smiley['Images not deleted'], implode(', ', $not_deleted));
	else 
		$message = $lang_smiley['Images deleted'];

	redirect(PLUGIN_URL, $message);
}

// Add an image
elseif (isset($_POST['add_image']))
{
	if (!isset($_FILES['req_file']))
		message($lang_smiley['No file']);
			
	$uploaded_file = $_FILES['req_file'];

	// Make sure the upload went smooth
	if (isset($uploaded_file['error']))
	{
		switch ($uploaded_file['error'])
		{
			case 1:	// UPLOAD_ERR_INI_SIZE
			case 2:	// UPLOAD_ERR_FORM_SIZE
				message($lang_smiley['Too large ini']);
				break;
	
			case 3:	// UPLOAD_ERR_PARTIAL
				message($lang_smiley['Partial upload']);
				break;
	
			case 4:	// UPLOAD_ERR_NO_FILE
				message($lang_smiley['No file']);
				break;
	
			case 6:	// UPLOAD_ERR_NO_TMP_DIR
				message($lang_smiley['No tmp directory']);
				break;
	
			default:
				// No error occured, but was something actually uploaded?
				if ($uploaded_file['size'] == 0)
					message($lang_smiley['No file']);
				break;
		}
	}
	
	if (is_uploaded_file($uploaded_file['tmp_name']))
	{
		$filename = substr($uploaded_file['name'], 0, strpos($uploaded_file['name'], '.'));
		
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if (!in_array($uploaded_file['type'], $allowed_types))
			message($lang_smiley['Bad type']);

		// Make sure the file isn't too big
		if ($uploaded_file['size'] > $smilies_config_image_size)
			message($lang_smiley['Too large'].' '.$smilies_config_image_size.' '.$lang_smiley['bytes'].'.');

		// Determine type
		$extensions = null;
		if ($uploaded_file['type'] == 'image/gif')
			$extensions = array('.gif', '.jpg', '.png');
		else if ($uploaded_file['type'] == 'image/jpeg' || $uploaded_file['type'] == 'image/pjpeg')
			$extensions = array('.jpg', '.gif', '.png');
		else
			$extensions = array('.png', '.gif', '.jpg');

		// Move the file to the avatar directory. We do this before checking the width/height to circumvent open_basedir restrictions.
		if (!@move_uploaded_file($uploaded_file['tmp_name'], PUN_ROOT.'img/smilies/'.$filename.'.tmp'))
			message($lang_smiley['Move failed']);

		// Now check the width/height
		list($width, $height, $type,) = getimagesize(PUN_ROOT.'img/smilies/'.$filename.'.tmp');
		if (empty($width) || empty($height) || $width > $smilies_config_image_width || $height > $smilies_config_image_height)
		{
			@unlink(PUN_ROOT.'img/smilies/'.$filename.'.tmp');
			message($lang_smiley['Too wide or high'].' '.$smilies_config_image_width.'x'.$smilies_config_image_height.' '.$lang_profile['pixels'].'.');
		}
		else if ($type == 1 && $uploaded_file['type'] != 'image/gif')	// Prevent dodgy uploads
		{
			@unlink(PUN_ROOT.'img/smilies/'.$filename.'.tmp');
			message($lang_smiley['Bad type']);
		}			

		// Delete any old avatars and put the new one in place
		@unlink(PUN_ROOT.'img/smilies/'.$filename.$extensions[0]);
		@unlink(PUN_ROOT.'img/smilies/'.$filename.$extensions[1]);
		@unlink(PUN_ROOT.'img/smilies/'.$filename.$extensions[2]);
		@rename(PUN_ROOT.'img/smilies/'.$filename.'.tmp', PUN_ROOT.'img/smilies/'.$filename.$extensions[0]);
		@chmod(PUN_ROOT.'img/smilies/'.$filename.$extensions[0], 0644);
	}
	else
		message($lang_smiley['Unknown failure']);

	redirect(PLUGIN_URL, $lang_smiley['Successful Upload']);
}

// Add a smilies to the list
elseif (isset($_POST['add_smiley']))
{
	$smiley_code = trim($_POST['smiley_code']);
	$smiley_image = trim($_POST['smiley_image']);
	
	if ($smiley_code == '')
		message($lang_smiley['Create Smiley Code None']);

	if ($smiley_image == '')
		message($lang_smiley['Create Smiley Image None']);
	
	if (in_array($smiley_code, $smiley_text))
		message($lang_smiley['Code already exists']);
	
	$db->query('INSERT INTO '.$db->prefix."smilies (image, text) VALUES ('".$smiley_image."', '".$db->escape($smiley_code)."')") or error('Unable to add smiley', __FILE__, __LINE__, $db->error());
	
	require_once PUN_ROOT.'include/cache_smilies.php';
	generate_smiley_cache();
	
	if (file_exists(PUN_ROOT.'include/cache_puntoolbar.php'))
	{
		require_once PUN_ROOT.'include/cache_puntoolbar.php';
		generate_ptb_cache();
		generate_ptb_cache('quickreply');
	}

	redirect(PLUGIN_URL, $lang_smiley['Successful Creation']);
}

// Diplaying
else {

	// Display the admin navigation menu
	generate_admin_menu($plugin);

?>
	<div class="block">
		<h2><span>Plugin Smilies v.<?php echo PLUGIN_VERSION; ?></span></h2>
		<div class="box">
			<div class="inbox">
				<p><?php echo $lang_smiley['Description'] ?></p>
			</div>
		</div>
	</div>

	<div class="blockform">
	
		<h2 class="block2"><span><?php echo $lang_smiley['Current Smilies'] ?></span></h2>
		<div class="box">
	<?php
	$result = $db->query('SELECT * FROM '.$db->prefix.'smilies ORDER BY disp_position') or error('Unable to retrieve smilies', __FILE__, __LINE__, $db->error());
	
	$num_db_smilies = $db->num_rows($result);
	
	if ($num_db_smilies > 0) : ?>
			<form method="post" action="<?php echo PLUGIN_URL; ?>">
				<div class="inform">
					<fieldset>
						<legend><?php echo $lang_smiley['List Current Smilies'] ?></legend>
						<div class="infldset">
						<table>
							<thead>
							<tr>
								<th scope="row"><?php echo $lang_smiley['Position']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Image Filename']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Code']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Image']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Remove']; ?></th>
							</tr>
							</thead>
							<tbody>
		<?php while ($db_smilies = $db->fetch_assoc($result)) : ?>
							<tr>
								<td><input type="text" name="smilies_order[<?php echo $db_smilies['id'] ?>]" value="<?php echo $db_smilies['disp_position']; ?>" size="3" maxlength="3" /></td>
								<td><?php echo $db_smilies['image']; ?></td>
								<td><input type="text" name="smilies_code[<?php echo $db_smilies['id'] ?>]" value="<?php echo $db_smilies['text'] ?>" size="5" maxlength="60" /></td>
								<td><img src="img/smilies/<?php echo $db_smilies['image'] ?>" alt="<?php echo pun_htmlspecialchars($db_smilies['text']) ?>" /></td>
								<td><input name="rem_smilies[<?php echo $db_smilies['id'] ?>]" type="checkbox" value="1" /></td>
							</tr>
		<?php endwhile; ?>
							</tbody>
						</table>
						</div>
					</fieldset>
				</div>
				<p class="submitend"><input name="reord" type="submit" value="<?php echo $lang_smiley['Edit smilies']; ?>" /> <input name="remove" type="submit" value="<?php echo $lang_smiley['Remove Selected']; ?>" /></p>
			</form>
	<?php else : ?>
			<div class="fakeform">
				<div class="inbox">
					<p><?php echo $lang_smiley['No smiley']; ?></p>
				</div>
			</div>
	<?php endif; ?>
			
			<form method="post" action="<?php echo PLUGIN_URL; ?>">
				<div class="inform">
					<fieldset>
						<legend><?php echo $lang_smiley['Submit New Smiley'] ?></legend>
						<div class="infldset">
						<table class="aligntop" cellspacing="0">
							<tr>
								<th scope="row"><?php echo $lang_smiley['Smiley Code'] ?></th>
								<td>
									<input type="text" name="smiley_code" size="25" tabindex="1" />
									<span><?php echo $lang_smiley['Smiley Code Description'] ?></span>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php echo $lang_smiley['Smiley Image'] ?></th>
								<td>
									<input type="text" name="smiley_image" size="25" tabindex="1" />
									<span><?php echo $lang_smiley['Smiley Image Description'] ?></span>
								</td>
							</tr>
						</table>
						</div>
					</fieldset>
				</div>
				<p class="submitend"><input type="submit" name="add_smiley" value="<?php echo $lang_smiley['Submit Smiley'] ?>" /></p>
			</form>
		</div>		
		
		<h2 class="block2"><span>Liste des images actuellement disponibles</span></h2>
		<div class="box">
			<form method="post" action="<?php echo PLUGIN_URL; ?>">
				<div class="inform">
					<fieldset>
						<legend><?php echo $lang_smiley['List Images Smilies'] ?></legend>
						<div class="infldset">
	<?php
	$img_smilies = array();
	$d = dir(PUN_ROOT.'img/smilies');
	while (($entry = $d->read()) !== false)
	{
		if ($entry != '.' && $entry != '..' && $entry != 'index.html')
			$img_smilies[] = $entry;
	}
	$d->close();
	@natsort($img_smilies);
	?>
						<table>
							<thead>
							<tr>
								<th scope="row"><?php echo $lang_smiley['Image Filename']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Image']; ?></th>
								<th scope="row"><?php echo $lang_smiley['Delete']; ?></th>
							</tr>
							</thead>
							<tbody>
<?php
$i = 0;
foreach ($img_smilies as $img) :
?>
							<tr>
								<td><?php echo $img; ?></td>
								<td><img src="img/smilies/<?php echo $img; ?>" alt="" /></td>
								<td><input name="del_smilies[<?php echo $img; ?>]" type="checkbox" value="1" /></td>
							</tr>
<?php
$i++;
endforeach;
?>
							</tbody>
						</table>
						</div>
					</fieldset>
				</div>
				<p class="submitend"><input name="delete" type="submit" value="<?php echo $lang_smiley['Delete Selected']; ?>" /></p>
			</form>
			
			<form method="post" enctype="multipart/form-data"  action="<?php echo PLUGIN_URL; ?>">
				<div class="inform">
					<fieldset>
						<legend><?php echo $lang_smiley['Add Images Smilies'] ?></legend>
						<div class="infldset">
							<label><?php echo $lang_smiley['Image file'] ?><br /><input name="req_file" type="file" size="40" /><br /></label>
						</div>
					</fieldset>
				</div>
				<p class="submitend"><input name="add_image" type="submit" value="<?php echo $lang_smiley['Upload']; ?>" /></p>
			</form>

		</div>
	</div>


<?php

}